﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace AuthCenter_API.Read.Architecture.Common
{
    public class JwtTools
    {
        /// <summary>
        ///     签发Token令牌
        /// </summary>
        /// <param name="_configuration"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public string JwtNewString(IConfiguration _configuration,string uid)
        {
            //生成JWT
            //Header,选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload，存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Name,"张三"),
                new Claim(ClaimTypes.Email,"zhangsan@example.com"),
                new Claim(ClaimTypes.Role,"Admin"),
                new Claim(ClaimTypes.DateOfBirth,"1980-01-01",ClaimValueTypes.Date),
                new Claim("CustomClaimType","CustomValue"),
                new Claim("key","value值"),
            };
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var siggnigKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signigCredentials = new SigningCredentials(siggnigKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken
            (
                issuer: _configuration["Authentication:Issuer"],//发布者
                audience: _configuration["Authentication:Audience"],//接收者
                claims: claims,//存放的用户信息
                notBefore:DateTime.UtcNow,//发布时间
                expires:DateTime.UtcNow.AddDays(1),//有效期设置为1天
                signigCredentials //数字签名
            );
            //生成token字符串
            var TokenSTr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenSTr;
        }
    }
}
